package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.TaoHuaApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.Audio;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.AudioVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class TaoHuaService {
    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference(version = "1.0.0")
    private TaoHuaApi taoHuaApi;
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    //发送语音
    public Object saveAudio(MultipartFile soundFile) {
        try {
            Audio audio = new Audio();
            audio.setUserId(UserThreadLocal.get());
            //上传语音条
            StorePath storePath = this.storageClient
                    .uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                            StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true), null);
            audio.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            String s = taoHuaApi.saveAudio(audio);
            if(!StrUtil.isEmpty(s)){
                return true;
            }
        } catch (Exception e) {
            String msg = StrUtil.format("发送语音失败！ soundFile = {}"
                    , soundFile.getOriginalFilename());
            log.error(msg, e);
        }
        return ErrorResult.builder().errCode("500").errMessage("次数已耗尽！").build();
    }

    //接收语音
    public AudioVo getAudio() {
        Long userId = UserThreadLocal.get();
        AudioVo audioVo = this.taoHuaApi.getAudio(userId);
        UserInfo userInfo = this.userInfoApi.queryByUserId(audioVo.getId());
        AudioVo voiceVo = BeanUtil.toBeanIgnoreError(userInfo, AudioVo.class);
        voiceVo.setGender(userInfo.getSex().toString().toLowerCase());
        voiceVo.setSoundUrl(audioVo.getSoundUrl());
        voiceVo.setRemainingTimes(audioVo.getRemainingTimes());
        return voiceVo;
    }
}
